#if UNITY_EDITOR
using System.Collections.Generic;
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEngine;

namespace JH
{
    /// <summary>
    ///  给文件夹添加一个样图展示，样图在文件夹下以"样图.png"命名
    /// </summary>
    [CustomEditor(typeof(DefaultAsset))]
    public class SampleImageFolderInspectorExtension : Editor
    {
        public override void OnInspectorGUI()
        {
            // 只对文件夹类型的资产显示扩展界面
            string assetPath = AssetDatabase.GetAssetPath(target);
            if (AssetDatabase.IsValidFolder(assetPath))
            {
                // 绘制样图
                DrawSampleImage(assetPath);
            }
        }

        /// <summary>
        /// 绘制样图
        /// </summary>
        private void DrawSampleImage(string assetPath)
        {
            //找到当前路径下的全部Texture2D资产
            var folders = AssetDatabase.FindAssets("t:Folder", new string[] { assetPath });
            var folderPaths = folders.Select(AssetDatabase.GUIDToAssetPath)
                .Where(path => path != null && path != assetPath).ToList();
            folderPaths.Add(assetPath);
            var assets = folderPaths.SelectMany(i =>
                AssetDatabase.FindAssets("t:Texture2D", new[] { i })).Distinct();
            var samplePathList = assets.Where(i =>
            {
                var directory = Path.GetDirectoryName(AssetDatabase.GUIDToAssetPath(i));
                if (directory == null) return false;
                return AssetDatabase.GUIDToAssetPath(i).Contains("样图") ||
                       AssetDatabase.GUIDToAssetPath(i).ToLower().Contains("sample");
            }).ToList();
            if (samplePathList.Count == 0)
            {
                DrawDefaultInspector();
                return;
            }

            //开启垂直布局
            EditorGUILayout.BeginVertical();

            //遍历每一个样图
            foreach (var each in samplePathList)
            {
                //加载图片
                var image = AssetDatabase.LoadAssetAtPath<Texture2D>(AssetDatabase.GUIDToAssetPath(each));
                if (image)
                {
                    // 使用水平布局
                    EditorGUILayout.BeginHorizontal();

                    // 在图片前添加灵活的空白空间
                    GUILayout.FlexibleSpace();

                    // 显示图片
                    if (image.width > 300 || image.height > 300)
                        GUILayout.Label(image, GUILayout.Width(300), GUILayout.Height(300));
                    else
                        GUILayout.Label(image, GUILayout.Width(image.width), GUILayout.Height(image.height));

                    // 在图片后也添加灵活的空白空间
                    GUILayout.FlexibleSpace();
                    EditorGUILayout.EndHorizontal();
                }
            }
        }
    }
}
#endif